/*
 * @Title:
 * @Description:
 * @Author: 靖博君
 * @Date: 2024-02-21 17:42:49
 * @FilePath: /vue3-admin-naive-starter/src/utils/request.ts
 */
import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios'
import qs from 'qs'
import whiteList from '@/config/white-list'
import { useLoginStore } from '@/stores/login'

export const CONTENT_TYPE = 'Content-Type'

export const FORM_URLENCODED = 'application/x-www-form-urlencoded; charset=UTF-8'

export const APPLICATION_JSON = 'application/json; charset=UTF-8'

export const TEXT_PLAIN = 'text/plain; charset=UTF-8'

const instance: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_GLOB_API_URL,
  timeout: import.meta.env.VITE_GLOB_API_TIMEOUT,
  headers: {
    [CONTENT_TYPE]: APPLICATION_JSON
  },
  // 参数序列化
  paramsSerializer: {
    serialize(params) {
      !params.t && (params.t = Date.now())
      return qs.stringify(params, { allowDots: true })
    }
  }
})

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const { url } = config
    const token = useLoginStore().token
    if (token) {
      const [tokenName = 'dcc-token-emp', tokenValue = '1'] = token.split('|')
      // console.log('tokenName', tokenName);
      // console.log('tokenValue', tokenValue);
      // 白名单中的请求不添加token
      if (!whiteList.some((i: string) => url?.includes(i) && tokenValue)) {
        config.headers.set(tokenName, tokenValue)
      }
    }
    return config
  },
  (error) => {
    return Promise.reject(error.response)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    const { status, data, headers } = response
    if (status === 200) {
      // 响应数据操作
      /**
       * 根据相应content-type判断是否是文件流，若是则直接返回
       * 需要后端定义好返回头参数content-type，注意大小写为小写
       * 返回相应可以在请求参数的responseType参数定义：
       * https://www.axios-http.cn/docs/req_config
       */
      if (headers['content-type'] && headers['content-type'].includes('application/octet-stream')) {
        return { data, status: 200, msg: '' }
      }
      const { status: code, msg } = data
      if (code === 200) {
        return data
      } else {
        return Promise.reject(data)
      }
    } else {
      return Promise.reject(data)
    }
  },
  (error) => {
    if (import.meta.env.MODE === 'development') {
      console.error('Request Error', error)
    }
    return Promise.reject({ code: 500, msg: '服务器异常，请稍后重试…' })
  }
)
export default instance
